#!/bin/bash

# ELAdmin Docker 镜像构建脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 默认配置
IMAGE_NAME="eladmin"
IMAGE_TAG="latest"
DOCKERFILE="Dockerfile"
BUILD_CONTEXT="."

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 显示帮助信息
show_help() {
    echo "ELAdmin Docker 镜像构建脚本"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  -n, --name IMAGE_NAME    镜像名称 (默认: eladmin)"
    echo "  -t, --tag IMAGE_TAG      镜像标签 (默认: latest)"
    echo "  -f, --file DOCKERFILE    Dockerfile路径 (默认: Dockerfile)"
    echo "  -c, --context CONTEXT    构建上下文 (默认: .)"
    echo "  --no-cache               不使用缓存构建"
    echo "  --push                   构建后推送到仓库"
    echo "  --registry REGISTRY      镜像仓库地址"
    echo "  --clean                  构建前清理旧镜像"
    echo "  --inspect                构建后检查镜像"
    echo "  -h, --help               显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0                                    # 使用默认配置构建"
    echo "  $0 -n eladmin -t v1.0.0              # 指定镜像名称和标签"
    echo "  $0 --no-cache --clean                 # 不使用缓存并清理旧镜像"
    echo "  $0 --push --registry my-registry.com # 构建并推送到指定仓库"
    echo ""
}

# 检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! docker info &> /dev/null; then
        print_error "Docker 服务未运行，请启动 Docker 服务"
        exit 1
    fi
    
    print_message "Docker 环境检查通过"
}

# 检查JAR包是否存在
check_jar() {
    # 使用 find 命令查找 JAR 包
    JAR_FILES=$(find eladmin-system/target -name "*.jar" 2>/dev/null)
    
    if [ -z "$JAR_FILES" ]; then
        print_warning "JAR 包不存在，开始构建..."
        if [ -f "build-jar.sh" ]; then
            ./build-jar.sh build
        else
            print_error "未找到 build-jar.sh 脚本，请手动构建 JAR 包"
            exit 1
        fi
    else
        print_message "JAR 包已存在: $(echo "$JAR_FILES" | head -1)"
    fi
}

# 清理旧镜像
clean_old_images() {
    print_step "清理旧镜像..."
    
    # 查找并删除旧的镜像
    OLD_IMAGES=$(docker images | grep "^${IMAGE_NAME}" | awk '{print $3}')
    
    if [ -n "$OLD_IMAGES" ]; then
        echo "$OLD_IMAGES" | xargs -r docker rmi -f
        print_message "已清理 $(echo "$OLD_IMAGES" | wc -l) 个旧镜像"
    else
        print_message "没有找到需要清理的旧镜像"
    fi
}

# 构建镜像
build_image() {
    print_step "开始构建 Docker 镜像..."
    
    # 构建命令
    BUILD_CMD="docker build"
    
    # 添加标签
    BUILD_CMD="$BUILD_CMD -t ${IMAGE_NAME}:${IMAGE_TAG}"
    
    # 添加latest标签（如果不是latest）
    if [ "$IMAGE_TAG" != "latest" ]; then
        BUILD_CMD="$BUILD_CMD -t ${IMAGE_NAME}:latest"
    fi
    
    # 添加Dockerfile
    BUILD_CMD="$BUILD_CMD -f ${DOCKERFILE}"
    
    # 添加构建上下文
    BUILD_CMD="$BUILD_CMD ${BUILD_CONTEXT}"
    
    # 添加no-cache选项
    if [ "$NO_CACHE" = "true" ]; then
        BUILD_CMD="$BUILD_CMD --no-cache"
    fi
    
    print_message "执行构建命令: $BUILD_CMD"
    
    # 执行构建
    if eval $BUILD_CMD; then
        print_message "镜像构建成功！"
        print_message "镜像名称: ${IMAGE_NAME}:${IMAGE_TAG}"
        
        # 显示镜像信息
        docker images | grep "^${IMAGE_NAME}"
    else
        print_error "镜像构建失败"
        exit 1
    fi
}

# 检查镜像
inspect_image() {
    print_step "检查镜像信息..."
    
    print_message "镜像详细信息:"
    docker inspect "${IMAGE_NAME}:${IMAGE_TAG}" | jq '.[0] | {Id, RepoTags, Created, Size, Architecture, Os}' 2>/dev/null || \
    docker inspect "${IMAGE_NAME}:${IMAGE_TAG}"
    
    print_message "镜像层信息:"
    docker history "${IMAGE_NAME}:${IMAGE_TAG}"
}

# 推送镜像
push_image() {
    if [ -n "$REGISTRY" ]; then
        print_step "推送镜像到仓库..."
        
        # 重新标记镜像
        FULL_IMAGE_NAME="${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}"
        docker tag "${IMAGE_NAME}:${IMAGE_TAG}" "$FULL_IMAGE_NAME"
        
        # 推送镜像
        if docker push "$FULL_IMAGE_NAME"; then
            print_message "镜像推送成功: $FULL_IMAGE_NAME"
        else
            print_error "镜像推送失败"
            exit 1
        fi
    else
        print_warning "未指定镜像仓库，跳过推送"
    fi
}

# 显示构建信息
show_build_info() {
    print_message "构建完成！"
    echo ""
    echo "镜像信息:"
    echo "  名称: ${IMAGE_NAME}"
    echo "  标签: ${IMAGE_TAG}"
    echo "  大小: $(docker images ${IMAGE_NAME}:${IMAGE_TAG} --format 'table {{.Size}}' | tail -n 1)"
    echo ""
    echo "使用命令:"
    echo "  docker run -d -p 8000:8000 ${IMAGE_NAME}:${IMAGE_TAG}"
    echo "  docker-compose up -d"
    echo ""
}

# 解析命令行参数
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -n|--name)
                IMAGE_NAME="$2"
                shift 2
                ;;
            -t|--tag)
                IMAGE_TAG="$2"
                shift 2
                ;;
            -f|--file)
                DOCKERFILE="$2"
                shift 2
                ;;
            -c|--context)
                BUILD_CONTEXT="$2"
                shift 2
                ;;
            --no-cache)
                NO_CACHE="true"
                shift
                ;;
            --push)
                PUSH_IMAGE="true"
                shift
                ;;
            --registry)
                REGISTRY="$2"
                shift 2
                ;;
            --clean)
                CLEAN_OLD="true"
                shift
                ;;
            --inspect)
                INSPECT_IMAGE="true"
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                print_error "未知选项: $1"
                show_help
                exit 1
                ;;
        esac
    done
}

# 主函数
main() {
    print_message "ELAdmin Docker 镜像构建脚本"
    echo "=================================="
    
    # 解析参数
    parse_args "$@"
    
    # 显示构建配置
    print_message "构建配置:"
    echo "  镜像名称: $IMAGE_NAME"
    echo "  镜像标签: $IMAGE_TAG"
    echo "  Dockerfile: $DOCKERFILE"
    echo "  构建上下文: $BUILD_CONTEXT"
    echo "  不使用缓存: ${NO_CACHE:-false}"
    echo "  清理旧镜像: ${CLEAN_OLD:-false}"
    echo "  检查镜像: ${INSPECT_IMAGE:-false}"
    echo "  推送镜像: ${PUSH_IMAGE:-false}"
    if [ -n "$REGISTRY" ]; then
        echo "  镜像仓库: $REGISTRY"
    fi
    echo ""
    
    # 检查环境
    check_docker
    
    # 检查JAR包
    check_jar
    
    # 清理旧镜像
    if [ "$CLEAN_OLD" = "true" ]; then
        clean_old_images
    fi
    
    # 构建镜像
    build_image
    
    # 检查镜像
    if [ "$INSPECT_IMAGE" = "true" ]; then
        inspect_image
    fi
    
    # 推送镜像
    if [ "$PUSH_IMAGE" = "true" ]; then
        push_image
    fi
    
    # 显示构建信息
    show_build_info
}

# 执行主函数
main "$@" 